<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="模块" prop="module">
        <el-input
          v-model="queryParams.module"
          placeholder="请输入模块"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="上传时间" prop="uploadTime">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.uploadTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择上传时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="上传账户" prop="uploadAccount">
        <el-input
          v-model="queryParams.uploadAccount"
          placeholder="请输入上传账户"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核账户" prop="checkAccount">
        <el-input
          v-model="queryParams.checkAccount"
          placeholder="请输入上传账户"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="checkStatus">
        <el-select v-model="queryParams.checkStatus" placeholder="请选择审核状态" clearable size="small">
          <el-option
            v-for="dict in checkStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['information:appSysResource:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['information:appSysResource:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-check"
          size="mini"
          :disabled="single"
          @click="handleCheckPass"
          v-hasPermi="['information:appSysResource:check']"
        >审核通过</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-close"
          size="mini"
          :disabled="single"
          @click="handleCheckNoPass"
          v-hasPermi="['information:appSysResource:check']"
        >审核不通过</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['information:appSysResource:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['information:appSysResource:export']"
        >导出</el-button>
      </el-col>
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery" />
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch" />
        </el-tooltip>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="appSysResourceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="类型" align="center" prop="type" :formatter="typeFormat" />
<!--      <el-table-column label="模块" align="center" prop="module" />-->
      <el-table-column label="缩略图" align="center" prop="url">
        <template slot-scope="scope">
          <div class="demo-image__preview">
            <el-image style="height: 30%;width: 30%" :src="scope.row.url" :zIndex="9999"
                      :preview-src-list="[scope.row.url]" @click.stop="handleClickItem"></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="图片地址" align="center" prop="showUrl" />
      <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
<!--        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d}') }}</span>
        </template>-->
      </el-table-column>
      <el-table-column label="上传账户" align="center" prop="uploadAccount" />
      <el-table-column label="审核时间" align="center" prop="checkTime" width="180">
<!--        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.checkTime, '{y}-{m}-{d}') }}</span>
        </template>-->
      </el-table-column>
      <el-table-column label="审核账户" align="center" prop="checkAccount" />
      <el-table-column label="审核状态" align="center" prop="checkStatus" :formatter="checkStatusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['information:appSysResource:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['information:appSysResource:remove']"
          >删除</el-button>-->
<!--          <el-button
            size="mini"
            type="text"
            icon="el-icon-copy-document"
            @click="copyToClipboard(scope.row)"
          >复制</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改系统资源库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类型">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-col>
            <el-form-item label="图片" prop="url">
              <el-upload
                class="upload-demo"
                :headers="headers"
                :action="uploadUrl" :show-file-list="false"
                :before-upload="beforeUpload"
                :on-success="uploadSuccess">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
              </el-upload>
              <p v-if="form.type==='img'">
                <img v-if="form.url" :src="form.url" :style="{height: '178px', display: 'block'}">
              </p>
              <p v-if="form.type==='video'">
                <video v-if="form.url" controls>
                  <source :src="form.url" type="video/mp4">
                </video>
              </p>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="路径" prop="showUrl">
          <el-input v-model="form.showUrl" placeholder="请输入路径" readonly/>
        </el-form-item>
<!--        <el-form-item label="项目" prop="project">
          <el-input v-model="form.project" placeholder="请输入项目" />
        </el-form-item>
        <el-form-item label="片区" prop="area">
          <el-input v-model="form.area" placeholder="请输入片区" />
        </el-form-item>
        <el-form-item label="模块" prop="module">
          <el-input v-model="form.module" placeholder="请输入模块" />
        </el-form-item>-->
<!--        <el-form-item label="上传时间" prop="uploadTime">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.uploadTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择上传时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上传账户" prop="uploadAccount">
          <el-input v-model="form.uploadAccount" placeholder="请输入上传账户" />
        </el-form-item>
        <el-form-item label="上传用户ID" prop="uploadUserId">
          <el-input v-model="form.uploadUserId" placeholder="请输入上传用户ID" />
        </el-form-item>
        <el-form-item label="上传用户名" prop="uploadUserName">
          <el-input v-model="form.uploadUserName" placeholder="请输入上传用户名" />
        </el-form-item>
        <el-form-item label="上传时间" prop="checkTime">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.checkTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择上传时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核账户" prop="checkAccount">
          <el-input v-model="form.checkAccount" placeholder="请输入审核账户" />
        </el-form-item>
        <el-form-item label="审核用户ID" prop="checkUserId">
          <el-input v-model="form.checkUserId" placeholder="请输入审核用户ID" />
        </el-form-item>
        <el-form-item label="审核用户名" prop="checkUserName">
          <el-input v-model="form.checkUserName" placeholder="请输入审核用户名" />
        </el-form-item>-->
        <el-form-item label="审核状态">
          <el-radio-group v-model="form.checkStatus">
            <el-radio
              v-for="dict in checkStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAppSysResource, getAppSysResource, delAppSysResource, addAppSysResource, updateAppSysResource, checkAppSysResource, getResourceBase64 } from "@/api/information/appSysResource";
import {getToken} from "@/utils/auth";

export default {
  name: "AppSysResource",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 系统资源库表格数据
      appSysResourceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型字典
      typeOptions: [],
      // 审核状态字典
      checkStatusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        module: null,
        uploadTime: null,
        uploadAccount: null,
        checkTime: null,
        checkAccount: null,
        checkStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      headers: { Authorization: "Bearer " + getToken() },
      uploadUrl: process.env.VUE_APP_BASE_API + '/system/ossFile/upload'
    };
  },
  created() {
    this.getList();
    this.getDicts("file_resource_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("CHECK_STATUS").then(response => {
      this.checkStatusOptions = response.data;
    });
  },
  methods: {
    /** 查询系统资源库列表 */
    getList() {
      this.loading = true;
      listAppSysResource(this.queryParams).then(response => {
        this.appSysResourceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 审核状态字典翻译
    checkStatusFormat(row, column) {
      return this.selectDictLabel(this.checkStatusOptions, row.checkStatus);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        url: null,
        project: null,
        area: null,
        module: null,
        uploadTime: null,
        uploadAccount: null,
        uploadUserId: null,
        uploadUserName: null,
        checkTime: null,
        checkAccount: null,
        checkUserId: null,
        checkUserName: null,
        checkStatus: "0",
        showUrl: null,
        resourceBase64: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加系统资源库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAppSysResource(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改系统资源库";
      });
    },
    copyToClipboard(row) {
      const checkStatus = row.checkStatus;
      if(checkStatus!='1'){
        this.msgError("未审核，不能复制");
      }
      const content = row.showUrl;
      this.$copyText(content).then(() => {
        // 复制成功时的操作
        console.log('内容已成功复制到剪贴板');
      }, () => {
        // 复制失败时的操作
        console.error('复制失败');
      });
    },
    handleCheckPass(row) {
      this.reset();
      const id = row.id || this.ids
      checkAppSysResource(id, 1).then(response => {
          if (response.code === 200) {
            this.msgSuccess("审核成功");
            this.getList();
          }
      });
    },
    handleCheckNoPass(row) {
      this.reset();
      const id = row.id || this.ids
      checkAppSysResource(id, 2).then(response => {
        if (response.code === 200) {
          this.msgSuccess("审核成功");
          this.getList();
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAppSysResource(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addAppSysResource(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除系统资源库编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAppSysResource(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('app/appSysResource/export', {
        ...this.queryParams
      }, `app_appSysResource.xlsx`)
    },
    //上传
    handleClickItem(row){
      this.$nextTick(() => {
        // 获取遮罩层dom
        let domImageMask = document.querySelector('.el-image-viewer__mask')
        if (!domImageMask) {
          return
        }
        domImageMask.addEventListener('click', () => {
          // 点击遮罩层时调用关闭按钮的 click 事件
          document.querySelector('.el-image-viewer__close').click()
        })
      })
    },
    uploadSuccess (response, file) {
      if (response && response.code === 200) {
        debugger;
        this.form.url = response.data;
        getResourceBase64('', this.form.url).then(response => {
          this.form.resourceBase64 = response.data;
        });
      } else {
        this.$message.error(response.msg)
      }
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      }
    },
    fetchAndConvertImage(url) {
      try {

      } catch (error) {
        console.error('Error fetching and converting image:', error);
      }
    }
  }
};
</script>
